package com.shuimin.group.mid.chat;

import com.shuimin.group.App;
import com.shuimin.group.mid.redis.RedisKey;
import com.shuimin.group.mid.redis.RedisService;
import com.shuimin.group.mid.redis.RedisUtil;
import com.shuimin.group.mid.time.AppTimer;
import com.shuimin.group.mid.time.Task_KeepAlive;
import com.shuimin.group.model.weixin.WeixinUser;
import pond.common.JSON;
import pond.common.S;
import pond.common.STRING;
import pond.web.Session;
import pond.web.WSCtx;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;

public class ChatService {

    public final static Map<String, WSCtx> ctxHolder = new ConcurrentHashMap<>();
    public final static Map<String, String> onlineUsers = new ConcurrentHashMap<>();

    //todo 一个用户多个登入，怎么处理（ onlineUsers 改成  userid ：list<sessionid> ，这样有个问题 session 过期如何删除干净）
    public static void add(Session session, WSCtx wsCtx) {
        WeixinUser weixinUser = session.get(App.APP_WEIXIN_USER_INFO);
        onlineUsers.put(weixinUser.id(), session.id());
        Task_KeepAlive keepAlive = new Task_KeepAlive(wsCtx);
        wsCtx.set("Task_KeepAlive", keepAlive.start(AppTimer.scheduledExecutorService));
        ctxHolder.put(session.id(), wsCtx);
        S.echo("*****ChatService add :", weixinUser.id() +"=" + session.id());
    }
    public static void remove(Session session) {
        if (ctxHolder.containsKey(session.id()))
        {
            WSCtx wsCtx = ctxHolder.get(session.id());
            TimerTask keepAlive = (TimerTask)wsCtx.get("Task_KeepAlive");
            if (keepAlive != null) {
                keepAlive.cancel();
            }
            ctxHolder.remove(session.id());
        }
        WeixinUser weixinUser = session.get(App.APP_WEIXIN_USER_INFO);
        if (onlineUsers.containsKey(weixinUser.id()))
        {
            onlineUsers.remove(weixinUser.id());
        }
        S.echo("$$$$$$ChatService remove:"+weixinUser.id()+"="+ session.id());
    }
    public static void handle(ChatEvent chatEvent) {
        S._assertNotNull(chatEvent);
        S.echo("handle");
        String groupId = chatEvent.getGroup_id();
        String key = RedisService.getGroupKeyById(groupId);
        if (STRING.isBlank(key))
        {
            S.echo(chatEvent.getGroup_id() + "not found");
            return;
        }
        List<String> memberKeyList = RedisUtil.keys(groupId+"*"+ RedisKey.MEMBER);
        List<Map<String, Object>> memberList = RedisUtil.hscanObjectFromKeys(memberKeyList);
        S.echo(memberList);
        if (ChatEventType.MESSAGE.val().equals(chatEvent.getType()))
        {
            Map<String, Map<String,String>> msgMap = new HashMap<>();
            Map<String, String> chatMap = new HashMap<>();
            S._for(memberList).each(member ->{
                String chart_record  = RedisService.getKey(chatEvent.getGroup_id(), member.get("user_id").toString(), RedisKey.CHAT_RECORD);
                String msg_key = chatEvent.getId() + RedisKey.CHAT_MSG ;
                Map<String, String> mapMsg = chatEvent.toJedisMap();
                //信息记录
                chatMap.put(chart_record, msg_key);
                S.echo("========= each member:"+JSON.stringify(member));
                if (!chatEvent.getUser_id().equals(member.get("user_id")))
                {
                    mapMsg.put("is_sender", "0");
                }
                else
                {
                    mapMsg.put("is_sender", "1");
                }
                S.echo("======= online:"+ onlineUsers.containsKey(member.get("user_id")) +"="+ JSON.stringify(onlineUsers) );
                if (onlineUsers.containsKey(member.get("user_id")))
                {
                    String sessionId = onlineUsers.get(member.get("user_id"));
                    S.echo("======= session :"+sessionId );
                    WSCtx wsCtx = ctxHolder.get(sessionId);
                    S.echo("######### send msg :"+ JSON.stringify(mapMsg));
                    wsCtx.sendTextFrame(JSON.stringify(mapMsg));
                }
                else
                {
                    S.echo("======= unread :"+ member.get("user_id"));
                    //未读信息
                    String chat_msg_unread  = RedisService.getKey(chatEvent.getGroup_id(), member.get("user_id").toString(), RedisKey.CHAT_MSG_UNREAD);
                    chatMap.put(chat_msg_unread, msg_key);
                }

                msgMap.put(msg_key, mapMsg);
            });
            if (RedisUtil.hAdd(msgMap))
            {
                RedisUtil.pushDiffStack(chatMap);
            }

        }

    }
}

